package com.swust.servlet;

import com.swust.service.LibServiceImpl;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

import static com.swust.common.Conf.LOGIN_USER;

@WebServlet(name = "LoginServlet",urlPatterns = "/LoginServlet")
public class LoginServlet extends HttpServlet {

    private static LibServiceImpl libService = new LibServiceImpl();

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String userName = request.getParameter("username");
        String password = request.getParameter("password");
        if (libService.login(userName, password)) {
            // 如果登陆成功
            request.getSession().setAttribute(LOGIN_USER, userName);
            response.sendRedirect(request.getContextPath() + "/view/server.jsp");
        } else {
            // 如果登陆失败
            // 返回一段登陆失败的字符串给登陆页面
            String loginMsg = "您的用户名或密码出现错误";
            request.setAttribute("loginMsg",loginMsg);
            request.getRequestDispatcher("/view/index.jsp").forward(request,response);
        }

    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doPost(request,response);
    }
}
